var express = require('express');
var router = express.Router();
const fs = require("fs");
const { uploadFiles, moveFiles, removeFiles } = require("../utils/uploadFiles");

// const multiparty = require("multiparty");
// router.post('/upload', function (req, res, next) {
//     const form = new multiparty.Form();
//     // 设置编码字符集
//     form.encoding = "utf-8";
//     // 文件储存路径
//     form.uploadDir = "./public/goodsFiles";
//     // 设置文件大小限制(2m)
//     form.maxFilesSize = 2 * 1024 * 1024;
//     // 解析请求
//     form.parse(req, function (err, fields, files) {
//         res.send(files);
//     });
//   });
const images = uploadFiles({
  path: "./public/temp",
  key: "file",
});
router.post("/uploadImages", async function (req, res, next) {
  // res.send(req.files[0].filename);
  images(req, res, function (err) {
    if (err) {
      if (err.code === "LIMIT_FILE_SIZE") {
        res.send({ success: false, msg: "文件过大" });
      }
    } else {
      res.send({ success: true, filename: req.files[0].filename });
    }
  });
});
router.post("/cacheImages", images, async function (req, res, next) {
  res.send(req.files[0].filename);
});

router.post("/deleteImages",async function (req, res, next) {
  // res.send(req.files[0].filename);
  // console.log("imgs",req.imgs);
  const { imgs } = req.body;
  console.log("img",imgs);
  
  if(imgs&&imgs!="defalut.jpg"){

    fs.unlinkSync("public/files/" +imgs, (err) => {
     
     if(err){

       console.log(err);
       res.send(err)
     }
     else{

       res.send("删除成功")
     }
      
    });
  
  
  }
});

module.exports = router;
